package com.blate.dogxiao.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 使用ViewDataBinding的RecyclerView.Adapter
 *
 * @author Az
 * on 2020/10/20
 */
public abstract class ViewBindingRecyclerViewAdapter<VB extends ViewDataBinding>
        extends RecyclerView.Adapter<ViewBindingRecyclerViewAdapter.ViewBindingHolder<VB>> {

    /**
     * 子类重写这个方法,提供ViewDataBinding
     *
     * @param inflater inflater
     * @param parent   parent
     * @param viewType viewType
     * @return VB
     */
    protected abstract VB onCreateBinding(LayoutInflater inflater, ViewGroup parent, int viewType);

    @NonNull
    @Override
    public ViewBindingHolder<VB> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewBindingHolder<>(onCreateBinding(LayoutInflater.from(parent.getContext()), parent, viewType));
    }

    public static class ViewBindingHolder<VB extends ViewDataBinding>
            extends RecyclerView.ViewHolder {

        protected VB mViewDataBinding;

        public ViewBindingHolder(@NonNull View itemView) {
            super(itemView);
        }

        public ViewBindingHolder(@NonNull VB binding) {
            this(binding.getRoot());
            this.mViewDataBinding = binding;
        }

        /**
         * 获取条目的ViewDataBinding
         *
         * @return VB
         */
        public VB getBinding() {
            return mViewDataBinding;
        }

    }

}
